<!-- 活动消息类型 -->
<template>
  <div class="temp-container">
    <!-- 消息名称 -->
    <el-form :model="operateForm" ref="operateForm" :rules="rules">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="col_title">消息名称</span>
        </div>
        <el-form-item label="消息名称" prop="name">
          <el-input
            class="common-left"
            clearable
            v-model="operateForm.name"
            maxlength="32"
            show-word-limit
            style="width:80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select
            class="common-left"
            style="width:80%"
            clearable
            v-model="operateForm.activityType"
            placeholder="请选择"
          >
            <el-option
              v-for="item in avtivityTypeList"
              :key="item.id"
              :label="item.note"
              :value="item.activityType"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-card>
      <!-- 发送用户 -->
      <el-card
        class="box-card"
        v-loading="loading"
        element-loading-text="正在计算选择的人数"
      >
        <div slot="header" class="clearfix">
          <span class="col_title">发送用户</span>
        </div>
        <el-form-item label="用户角色" prop="configData.userType">
          <el-radio-group
            v-model="operateForm.configData.userType"
            class="common-left"
          >
            <el-radio label="CONSULTANT">顾问</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="用户范围"
          prop="configData.consultantConfig.userRange"
        >
          <el-radio-group
            v-model="operateForm.configData.consultantConfig.userRange"
            class="common-left"
            @change="selectUserScope"
          >
            <el-radio
              v-for="item in userScope"
              :key="item.dictValue"
              :label="item.dictValue"
              >{{ item.dictLabel }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="选择学院"
          prop="configData.consultantConfig.collegeIds"
          v-if="
            operateForm.configData.consultantConfig.userRange ===
              'COLLEGE_CONSULTANT'
          "
        >
          <el-checkbox
            class="common-left"
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全部学院</el-checkbox
          >
          <el-checkbox-group
            class="common-left"
            v-model="operateForm.configData.consultantConfig.collegeIds"
            @change="handleCheckedCollegeIdsChange"
          >
            <el-checkbox
              v-for="item in colleges"
              :label="item.id"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          prop="consultantCount"
          v-if="
            operateForm.configData.consultantConfig.userRange ===
              'IMPORT_CONSULTANT'
          "
        >
          <span class="common-left"
            >共{{ operateForm.consultantCount || 0 }}人</span
          >
          <el-button
            type="success"
            icon="el-icon-plus"
            style="margin-left:10px"
            @click="params.centerDialogVisible = true"
            >批量导入</el-button
          >
          <el-button
            type="success"
            icon="el-icon-minus"
            @click="clearAllCounselor"
            >全部清空</el-button
          >
        </el-form-item>
        <el-form-item v-show="isShowViewNum">
          <div class="view-total" @click="viewsNum">
            查看人数
          </div>
        </el-form-item>
      </el-card>
      <!-- 发送内容 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="col_title">发送内容</span>
        </div>
        <el-form-item label="标题" prop="message.title">
          <el-input
            class="common-left"
            clearable
            v-model="operateForm.message.title"
            maxlength="32"
            show-word-limit
            style="width:80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="编辑内容" prop="message.content">
          <el-input
            type="textarea"
            style="width:80%"
            class="common-left"
            :rows="10"
            v-model="operateForm.message.content"
            maxlength="300"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="图片">
          <uploadSingImg
            class="common-left"
            :imgUrl="operateForm.message.backstageImage"
            accept=".jpg,.jpeg,.png,.gif"
            :maxSize="10"
            :WHScale="[0.7, 0.8, '3 : 4']"
            :showDeleteIcon="true"
            @getImgUrl="getMessageImg"
          >
            <template v-slot:imgInfo>（单张图片不可超过10M）</template>
          </uploadSingImg>
        </el-form-item>
        <el-form-item label="附件" prop="message.annexes">
          <uploadFiles
            class="common-left"
            :files-list="operateForm.message.annexes"
            @getFilesUrl="getFilesUrl"
            @deleteFile="deleteFile"
          ></uploadFiles>
        </el-form-item>
      </el-card>
      <!-- 发送时间 -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="col_title">发送时间</span>
        </div>
        <el-form-item label="选择时间" prop="configData.sendTimeType">
          <el-radio-group
            v-model="operateForm.configData.sendTimeType"
            class="common-left"
          >
            <el-radio label="SEND_IMMEDIATELY">立即发送</el-radio>
            <el-radio label="TIMED_SENDING">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="configData.sendTime"
          v-if="operateForm.configData.sendTimeType === 'TIMED_SENDING'"
        >
          <el-date-picker
            class="common-left"
            v-model="operateForm.configData.sendTime"
            type="datetime"
            size="small"
            placeholder="选择日期时间"
            value-format="timestamp"
          >
          </el-date-picker>
        </el-form-item>
        <div class="row_center">
          <el-button type="success" @click="submitForm('operateForm')"
            >保存</el-button
          >
          <el-button type="info" @click="cancle">取消</el-button>
        </div>
      </el-card>
    </el-form>
    <selectedNumDialog :formLimit="formLimit"></selectedNumDialog>
    <CommonImportDialog
      :params="params"
      @importSuccess="importSuccess"
      @importFail="importFail"
    />
    <CommomSucessDialog :successParams="successParams" />
    <CommonFailDialog :failParams="failParams" />
  </div>
</template>

<script>
import { clearTagMixins } from '@/mixins/clearTag'
import {
  collegeList,
  counselorNum,
  activityTypes,
  createActivity,
  templateData,
  editActivity
} from '@/api/notice'
import selectedNumDialog from '@/components/messageManagement/template/selectedNumDialog'
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import CommonImportDialog from '@/components/common/commonImportDialog/commonImportDialog'
import CommomSucessDialog from '@/components/common/commonImportDialog/commomSucessDialog'
import CommonFailDialog from '@/components/common/commonImportDialog/commonFailDialog'
import uploadFiles from '@common/uploadFiles'

export default {
  name: 'activityMessage',
  mixins: [clearTagMixins],
  data() {
    var validateCount = (rule, value, callback) => {
      !value ? callback(new Error('请导入指定顾问工号')) : callback()
    }
    return {
      loading: false,
      isIndeterminate: false,
      checkAll: false,
      colleges: [],
      userScope: [
        { dictLabel: '全部顾问', dictValue: 'ALL' },
        { dictLabel: '指定学顾问', dictValue: 'COLLEGE_CONSULTANT' },
        { dictLabel: '导入用户', dictValue: 'IMPORT_CONSULTANT' }
      ],
      operateForm: {
        name: '', //消息名称
        activityType: '', //活动类型
        consultantCount: null, //导入人数
        userDataId: '',
        message: {
          title: '', //内容标题
          content: '', //发送内容
          annexes: [], //附件
          type: 'BACKSTAGE',
          backstageImage: ''
        },
        messageTemplateAlias: 'ACTIVITY_MESSAGE_TEMPLATE',
        messageChannels: [],
        configData: {
          consultantConfig: {
            collegeIds: [], //学院列表
            userRange: '' //顾问范围
          },
          sendTime: '', //发送时间
          sendTimeType: '', //发送类型
          userType: 'CONSULTANT' //通知的用户类型  ///
        }
      },
      avtivityTypeList: [],
      formLimit: {
        visible: false,
        value: ''
      },
      params: {
        centerDialogVisible: false,
        title: '导入工号',
        downLoadFileName: '导入工号表'
      },
      successParams: {
        centerDialogVisible: false,
        successText: ''
      },
      failParams: {
        centerDialogVisible: false,
        failText: ''
      },
      rules: {
        name: [{ required: true, message: '请输入消息名称', trigger: 'blur' }],
        activityType: [
          { required: true, message: '请选择活动类型', trigger: 'change' }
        ],
        'configData.userType': [{ required: true, trigger: 'change' }],
        'configData.consultantConfig.userRange': [
          { required: true, message: '请选择用户范围', trigger: 'change' }
        ],
        consultantCount: [{ validator: validateCount, trigger: 'change' }],
        'configData.consultantConfig.collegeIds': [
          { required: true, message: '请选择学院', trigger: 'change' }
        ],
        'message.title': [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        'message.content': [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ],
        'configData.sendTimeType': [
          { required: true, message: '请选择发送时间', trigger: 'change' }
        ],
        'configData.sendTime': [
          { required: true, message: '请选择发送时间', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    selectedNumDialog,
    uploadSingImg,
    CommonImportDialog,
    CommomSucessDialog,
    CommonFailDialog,
    uploadFiles
  },
  watch: {
    $route: {
      handler(newV) {
        if (newV) {
          this.getTemplateData(newV.query.id)
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    //获取活动类型
    activityTypes({}, (res) => {
      this.avtivityTypeList = res
    })
    //获取学院
    collegeList({}, (res) => {
      this.colleges = res
    })
  },
  methods: {
    //获取详情
    getTemplateData(id) {
      if (id) {
        templateData(id, (res) => {
          let sendTime = Date.parse(new Date(res.configData.sendTime))
          this.operateForm = res
          this.operateForm.message = res.messageChannels[0]
          this.operateForm.userDataId = ''
          if (
            res.status === 'WITHDRAWN' &&
            res.configData.sendTimeType === 'SEND_IMMEDIATELY'
          ) {
            this.operateForm.configData.sendTimeType = ''
            this.operateForm.configData.sendTime = ''
          } else if (
            res.status === 'WITHDRAWN' &&
            res.configData.sendTimeType === 'TIMED_SENDING'
          ) {
            this.operateForm.configData.sendTime = ''
          } else {
            this.operateForm.configData.sendTime =
              res.configData.sendTimeType === 'TIMED_SENDING' ? sendTime : ''
          }
          let checkLength = res.configData.consultantConfig.collegeIds.length
          this.checkAll = checkLength === this.colleges.length
          this.isIndeterminate = checkLength < this.colleges.length
        })
      } else {
        Object.assign(this.$data.operateForm, this.$options.data().operateForm)
        this.$nextTick(() => {
          this.$refs['operateForm'].clearValidate()
        })
      }
    },
    //选择用户范围
    selectUserScope(val) {
      if (val !== 'COLLEGE_CONSULTANT') {
        this.operateForm.configData.consultantConfig.collegeIds = []
      }
      this.$refs['operateForm'].clearValidate([
        'consultantCount',
        'configData.consultantConfig.collegeIds'
      ])
    },
    //上传图片
    getMessageImg(url) {
      this.operateForm.message.backstageImage = url
    },
    //上传附件
    getFilesUrl(val) {
      val.forEach((item) => {
        this.operateForm.message.annexes.push({
          name: item.name,
          url: item.url
        })
      })
    },
    //删除附件
    deleteFile(val) {
      const res = this.operateForm.message.annexes.filter((item) => {
        return item.uid !== val
      })
      this.operateForm.message.annexes = res
    },
    //导入
    importSuccess(val) {
      let operaConcatForm = this.operateForm.userDataId
        .concat(',')
        .concat(val.userDataId)
      this.operateForm.userDataId = this.operateForm.userDataId
        ? Array.from(new Set(operaConcatForm.split(','))).join(',') //userdataid去重
        : val.userDataId
      this.params.centerDialogVisible = false
      this.successParams.centerDialogVisible = true
      this.successParams.successText = `成功导入用户${val.importCount}人`
      this.operateForm.consultantCount = val.importCount
    },
    //导入失败
    importFail(val) {
      this.params.centerDialogVisible = false
      this.failParams.centerDialogVisible = true
      this.failParams.failText = val
    },
    //全部清空
    clearAllCounselor() {
      this.operateForm.consultantCount = 0
      this.operateForm.userDataId = ''
    },
    //全选学院
    handleCheckAllChange(val) {
      let arr = this.colleges.map((item) => {
        return item.id
      })
      this.operateForm.configData.consultantConfig.collegeIds = val ? arr : []
      this.isIndeterminate = false
    },
    //选择学院
    handleCheckedCollegeIdsChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.colleges.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.colleges.length
    },
    //查看人数
    viewsNum() {
      this.loading = true
      const { userRange } = this.operateForm.configData.consultantConfig
      let obj = {}
      if (userRange === 'ALL') {
        let arr = []
        this.colleges.forEach((item) => {
          arr.push(item.id)
        })
        obj = { collegeIds: arr.join(',') }
      } else {
        if (!this.operateForm.configData.consultantConfig.collegeIds.length) {
          this.$message.warning('请至少选择一个学院')
          this.loading = false
          return
        }
        const { collegeIds } = this.operateForm.configData.consultantConfig
        obj = { collegeIds: collegeIds.join(',') }
      }
      counselorNum(
        obj,
        (res) => {
          this.loading = false
          this.formLimit.visible = true
          this.formLimit.value = `您本次选择了${res}人`
        },
        (err) => {
          this.loading = false
        }
      )
    },
    //保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        let id = this.$route.query.id
        if (valid) {
          this.operateForm.messageChannels = []
          this.operateForm.messageChannels.push(this.operateForm.message)
          if (id) {
            const { status } = this.operateForm
            if (status === 'WITHDRAWN') {
              createActivity(this.operateForm, () => {
                this.$message.success('创建成功')
                this.clearTag()
              })
            } else {
              editActivity(id, this.operateForm, () => {
                this.$message.success('修改成功')
                this.clearTag()
              })
            }
          } else {
            createActivity(this.operateForm, () => {
              this.$message.success('创建成功')
              this.clearTag()
            })
          }
        }
      })
    },
    //取消
    cancle() {
      this.clearTag()
    },
    /*退出*/
    signOut() {
      this.$router.go(-1)
    }
  },
  computed: {
    isShowViewNum() {
      const isShow =
        this.operateForm.configData.consultantConfig.userRange &&
        this.operateForm.configData.consultantConfig.userRange !==
          'IMPORT_CONSULTANT'
      return isShow
    }
  }
}
</script>

<style lang="less" scoped>
:deep(.el-button--primary) {
  background: #03be91 !important;
  border-color: #68cab3 !important;
}
:deep(.common-left) {
  margin-left: 100px !important;
}
:deep(.el-form-item__content) {
  margin-left: 100px;
}
:deep(.el-form-item__error) {
  margin-left: 100px;
}
.col_title {
  color: rgb(51, 51, 51);
  font-size: 20px;
  font-weight: 700;
}
.view-total {
  color: #03af81;
  margin-left: 100px;
  cursor: pointer;
}
.row_center {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px 0;
}
</style>
